package com.gitee.candy.file;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 图片缩略图
 *
 * @author
 * @version V1.0
 * @Description: https://blog.csdn.net/shuchongqu/article/details/84791122 解决外部字体问题
 * <p>
 * TODO 1.图片加文字水印
 * TODO 2.图片合成
 * TODO 3.生成缩略图
 * TODO 4.图片加水印
 * TODO 5.引用外部字体
 */
public class ImageHelper {
    public static ImageHelper me = new ImageHelper();

    /**
     * 生成缩略图 <br/>保存:ImageIO.write(BufferedImage, imgType[jpg/png/...], File);
     *
     * @param source 原图片
     * @param target 目标图片
     * @param width  缩略图宽
     * @param height 缩略图高
     * @param b      是否等比缩放
     */
    public void Thumb(String source, String target, int width, int height, boolean b) throws Exception {
        // targetW，targetH分别表示目标长和宽
        BufferedImage source_ = ImageIO.read(new File(source));
        int type = source_.getType();
        BufferedImage target_temp = null;
        double sx = (double) width / source_.getWidth();
        double sy = (double) height / source_.getHeight();

        if (b) {
            if (sx > sy) {
                sx = sy;
                width = (int) (sx * source_.getWidth());
            } else {
                sy = sx;
                height = (int) (sy * source_.getHeight());
            }
        }

        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source_.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(width,
                    height);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target_temp = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target_temp = new BufferedImage(width, height, type);
        }
        Graphics2D g = target_temp.createGraphics();
        // smoother than exlax:
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source_, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        ImageIO.write(target_temp, "jpg", new File(target));
//        return target;
    }

    /**
     * 生成缩略图 <br/>保存:ImageIO.write(BufferedImage, imgType[jpg/png/...], File);
     *
     * @param source 原图片
     * @param target 目标图片
     * @param width  缩略图宽
     * @param height 缩略图高
     */
    public void Thumb(String source, String target, int width, int height) throws Exception {
        // targetW，targetH分别表示目标长和宽
        BufferedImage source_ = ImageIO.read(new File(source));
        int type = source_.getType();
        BufferedImage target_temp = null;
        int sw = source_.getWidth();
        int sh = source_.getHeight();
        if ((sw / sh) > width / height) {//高度不够
            sw = sh * width / height;
        } else {//宽度不够或一致
            sh = sw * height / width;
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source_.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(width,
                    height);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target_temp = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target_temp = new BufferedImage(width, height, type);
        }
        Graphics2D g = target_temp.createGraphics();
        // smoother than exlax:
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
//        g.drawRenderedImage(source_, AffineTransform.getScaleInstance(sw, sh));
        g.drawImage(source_.getScaledInstance(sw, sh, Image.SCALE_SMOOTH), 0, 0, null);
        g.dispose();
        ImageIO.write(target_temp, "jpg", new File(target));
    }

    /**
     * 图片水印
     *
     * @param imgPath  待处理图片
     * @param saveFile 保存的图片
     * @param markPath 水印图片
     * @param x        水印位于图片左上角的 x 坐标值
     * @param y        水印位于图片左上角的 y 坐标值
     * @param alpha    水印透明度 0.1f ~ 1.0f
     */
    public void waterMark(String imgPath, String saveFile, String markPath, int x, int y, float alpha) {
        try {
            // 加载待处理图片文件
            Image img = ImageIO.read(new File(imgPath));

            BufferedImage image = new BufferedImage(img.getWidth(null), img
                    .getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(img, 0, 0, null);

            // 加载水印图片文件
            Image src_biao = ImageIO.read(new File(markPath));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src_biao, x, y, null);
            g.dispose();

            // 保存处理后的文件
//            FileOutputStream out = new FileOutputStream(saveFile);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(image);
//            out.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    /**
     * 文字水印
     *
     * @param imgPath 待处理图片
     * @param text    水印文字
     * @param font    水印字体信息
     * @param color   水印字体颜色
     * @param x       水印位于图片左上角的 x 坐标值
     * @param y       水印位于图片左上角的 y 坐标值
     * @param alpha   水印透明度 0.1f ~ 1.0f
     */

    public static void textMark(String imgPath, String text, Font font,
                                Color color, int x, int y, float alpha) {
        try {
            Font Dfont = (font == null) ? new Font("宋体", 20, 13) : font;

            Image img = ImageIO.read(new File(imgPath));

            BufferedImage image = new BufferedImage(img.getWidth(null), img
                    .getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();

            g.drawImage(img, 0, 0, null);
            g.setColor(color);
            g.setFont(Dfont);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawString(text, x, y);
            g.dispose();
//            FileOutputStream out = new FileOutputStream(imgPath);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(image);
//            out.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    /**
     * 图片添加水印
     *
     * @param srcImgPath       需要添加水印的图片的路径
     * @param outImgPath       添加水印后图片输出路径
     * @param typefacePath     字体路径
     * @param markContentColor 水印文字的颜色
     * @param fontSize         文字大小
     * @param waterMarkContent 水印的文字
     */
    public static void waterPress(String srcImgPath,
                                  String outImgPath,
                                  String typefacePath,
                                  Color markContentColor,
                                  int fontSize,
                                  String waterMarkContent) {
        try {
            // 读取原图片信息
            Long t1 = System.currentTimeMillis();
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            Long t2 = System.currentTimeMillis();
            System.out.println(("读取图片耗时(ms):" + (t2 - t1)));
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);

            g.setColor(markContentColor);//根据图片的背景设置水印颜色
            int y = 530;
            int tempX = 270;
            int tempY = y;
            String[] contents = waterMarkContent.split("\n");
            int j = 0;
            Font definedFont;
            definedFont = Font.createFont(Font.TRUETYPE_FONT, new File(typefacePath));
            for (String st : contents) {
                g.setFont(definedFont);
                if (j == 0) {
                    definedFont = definedFont.deriveFont(Font.PLAIN, fontSize + 30);
                } else {
                    definedFont = definedFont.deriveFont(Font.PLAIN, fontSize);
                }
                g.setFont(definedFont);
                j++;
                g.drawString(st, tempX, tempY);
                tempY += fontSize + 32;
            }
            g.dispose();
            Long t3 = System.currentTimeMillis();
            System.out.println(("写文字耗时(ms):" + (t3 - t2)));
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "png", outImgStream);
            outImgStream.flush();
            outImgStream.close();
            Long t4 = System.currentTimeMillis();
            System.out.println(("输出图片耗时(ms):" + (t4 - t3)));
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }

    public static void outAllFont() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontList = ge.getAvailableFontFamilyNames();
        System.out.println("共：" + fontList.length + "种字体");
        for (String f : fontList) {
            System.err.println(f);
        }
    }

    public static void main(String[] args) {
        String msg = "苏 苏 先生：\n" +
                "    2020年10月10日,是你在公司度过的第三个生日。\n" +
                "    在这个特别的日子里，我代表公司领导及全体员工，\n" +
                "感谢你为公司做出的贡献！";
        waterPress("C:\\Users\\lenovo\\Desktop\\birth\\birth123.jpg",
                "C:\\Users\\lenovo\\Desktop\\birth\\birth123.jpg",
                "C:\\Users\\lenovo\\Desktop\\birth\\FZXKJW.TTF",
                new Color(32, 91, 123), 88, msg);
    }
}